//
//  UserInfoViewController.m
//  danpin
//
//  Created by chuangjia on 26/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "UserInfoViewController.h"
#import "ZShare.h"
#import "NSString+Extensions.h"
#import "UIImageView+WebCache.h"
#import "UserAdressViewController.h"

#import "UserNickNameViewController.h"
#import "BaiChuanShare.h"
#import "ZPlatformShare.h"
#import "BaseModel.h"
#import "ZToastManager.h"
@interface UserInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@end

@implementation UserInfoViewController
@synthesize sectionArray=_sectionArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"我的账号";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    _sectionArray=[NSMutableArray arrayWithObjects:@"userinfo",@"addressinfo",@"systeminfo",@"comment",@"logout", nil];
    NSDictionary *dict =[[ZShare sharedInstance] userInfo];
    NSString *nickname =[NSString stringWithFormat:@"%@",[dict objectForKey:@"nick_name"]];
    NSString *largeFace =[NSString stringWithFormat:@"%@",[dict objectForKey:@"largeFace"]];
    if (nickname.length==0 &&largeFace.length==0)
    {
        [_sectionArray removeObject:@"userinfo"];
    }
    
    [self initUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    self.tbView = nil;
    self.sectionArray = nil;
}

-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sectionTitle =[_sectionArray objectAtIndex:section];
    if ([sectionTitle isEqualToString:@"userinfo"])
    {
        return 2;
    }else if ([sectionTitle isEqualToString:@"addressinfo"])
    {
        return 1;
        
    }else if ([sectionTitle isEqualToString:@"systeminfo"])
    {
        return 1;
    }else if([sectionTitle isEqualToString:@"comment"])
    {
        return 1;
    }else if ([sectionTitle isEqualToString:@"logout"])
    {
        return 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *sectionTitle =[_sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"userinfo"])
    {
        if(indexPath.row==0)
        {
            return 60;
        }else if (indexPath.row==1)
        {
            return 40;
        }
    }else if ([sectionTitle isEqualToString:@"addressinfo"])
    {
        return 40;
        
    }else if ([sectionTitle isEqualToString:@"systeminfo"])
    {
        return 40;
        
    }else if([sectionTitle isEqualToString:@"comment"])
    {
        return 40;
    }else if ([sectionTitle isEqualToString:@"logout"])
    {
        return 40;
    }
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    NSString *sectionTitle =[_sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"userinfo"])
    {
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = FONT(14);
            cell.textLabel.textColor = [UIColor grayColor];
        }
        NSDictionary *dict =[[ZShare sharedInstance] userInfo];
        NSString *nickname =[NSString stringWithFormat:@"%@",[dict objectForKey:@"nick_name"]];
        NSString * strURL =[[NSString stringWithFormat:@"%@", [dict objectForKey:@"largeFace"]] replaceNullString];
        switch (indexPath.row) {
            case 0:
            {
                cell.textLabel.text = @"头像";
                UIImageView *images =[[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width-90, 5, 50, 50)];
                images.contentMode=UIViewContentModeScaleToFill;
                [images sd_setImageWithURL:[NSURL URLWithString:strURL] placeholderImage:[UIImage imageNamed:@"user_face.png"]];
                [cell addSubview:images];
                images=nil;
            }
                break;
            case 1:
            {
                cell.textLabel.text = @"名字";
                UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, tableView.frame.size.width-120, 20)];
                lbl.backgroundColor=[UIColor clearColor];
                lbl.textColor =[UIColor grayColor];
                lbl.textAlignment = NSTextAlignmentRight;
                lbl.font = FONT(14);
                lbl.text=nickname;
                [cell addSubview:lbl];
                lbl=nil;
            }
                break;
            default:
                break;
        }
        return cell;
        
    }else if ([sectionTitle isEqualToString:@"addressinfo"])
    {
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = FONT(14);
            cell.textLabel.textColor = [UIColor grayColor];
        }
        cell.textLabel.text = @"地址管理";
        return cell;
        
    }else if ([sectionTitle isEqualToString:@"systeminfo"])
    {
//        static NSString *CellIdentifier = @"setWifiCell";
//        SettingCommonCell *cell = (SettingCommonCell*)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = FONT(14);
            cell.textLabel.textColor = [UIColor grayColor];
        }
        cell.textLabel.font = FONT(14);
        cell.textLabel.textColor = [UIColor grayColor];
        NSString *sizestr=@"";
        CGFloat size = [[SDImageCache sharedImageCache] getSize];
        if(size > 10)
        {
            if(size < 1000)
            {
                sizestr =[NSString stringWithFormat:@"%.0f B",size];
            }
            else if(size < 1000 * 1000)
            {
                sizestr =[NSString stringWithFormat:@"%.2f KB",size / 1000];
            }
            else
            {
                sizestr =[NSString stringWithFormat:@"%.2f MB",size / 1000 / 1000];
            }
        }
        if (sizestr.length==0) {
            cell.textLabel.text = [NSString stringWithFormat:@"清除缓存"];
        }else{
            cell.textLabel.text = [NSString stringWithFormat:@"清除缓存 (%@)",sizestr];
        }
        
        return cell;
        
    }else if([sectionTitle isEqualToString:@"comment"])
    {
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.textLabel.font = FONT(14);
            cell.textLabel.textColor = [UIColor grayColor];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text =@"给我们评价";
        return cell;
    }else if ([sectionTitle isEqualToString:@"logout"])
    {
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.textLabel.font = FONT(14);
            cell.textLabel.textColor = [UIColor grayColor];
        }
        cell.textLabel.text =@"退出登陆";
        return cell;
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *sectionTitle =[_sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"userinfo"])
    {
        if (indexPath.row==0) {
            if ([self isLogin]) {
                UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                              initWithTitle:nil
                                              delegate:self
                                              cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"相册选择",nil];
                actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
                [actionSheet showInView:self.view];
            }
        }else if (indexPath.row==1) {
            
            
            if ([self isLogin])
            {
                UserNickNameViewController *nick =[[UserNickNameViewController alloc] init];
                [nick setSelectedCallBack:^(id data, id key) {
                    [_tbView reloadData];
                }];
                [self presentViewController:nick animated:YES completion:nil];
                nick=nil;
            }
        }
    }else if ([sectionTitle isEqualToString:@"addressinfo"])
    {
        UserAdressViewController *adress  =[[UserAdressViewController alloc] init];
        [self.navigationController pushViewController:adress animated:YES];
        adress=nil;
        
    }else if ([sectionTitle isEqualToString:@"systeminfo"])
    {
        [[ZToastManager ShardInstance] showprogress];
        [[ZShare sharedInstance] cleanCache];
        [[ZToastManager ShardInstance] hideprogress];
        [[ZToastManager ShardInstance] showtoast:@"缓存清除成功"];
        
        [_tbView reloadData];
        
    }else if([sectionTitle isEqualToString:@"comment"])
    {
        //去购买的统计页面
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        [dict setValue:@"appstore_comment" forKey:@"action"];
        [dict setValue:@"" forKey:@"source"];
        [dict setValue:@"" forKey:@"type"];
        [dict setValue:@"" forKey:@"can_buy"];
        [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
            
        } failure:^(NSError *error) {
            
        }];
        
        NSString *str = @"itms-apps://itunes.apple.com/app/id1006667886";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        return;
        
    }else if ([sectionTitle isEqualToString:@"logout"])
    {
        if ([self isLogin]) {
            [[BaiChuanShare sharedInstance] logout];
            [ZPlatformShare logout];
            __weak typeof (self) wSelf = self;
            [BaseModel loginOut:nil success:^(AFHTTPRequestOperation *operation, id result) {
                [[ZToastManager ShardInstance] showtoast:[result objectForKey:@"msg"]];
                
                [[ZShare sharedInstance] setUserInfo:nil];
                [ZShare sharedInstance].sharecode_key=nil;
                [ZShare sharedInstance].sharelist_key=nil;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginout" object:nil];
                [wSelf.navigationController popToRootViewControllerAnimated:YES];
                
                
            } failure:^(NSError *error) {
                [ZShare hiddenAnimationView:wSelf.view text:@""];
            }];
        }
        
    }
}
#pragma usericon
//

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        DLog(@"模拟其中无法打开照相机,请在真机中使用");
        
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* imageo = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *image = [self scaleImage:imageo toScale:0.3];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //图片保存的路径
        [[ZToastManager ShardInstance] showprogress];
        [self upLoadIcon:image name:nil];
    }
}
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    DLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)upLoadIcon:(UIImage *)image name:(NSString *)name
{
    [BaseModel userinfo:name image:image success:^(AFHTTPRequestOperation *operation, id resultObject) {
        
        [[ZToastManager ShardInstance] hideprogress];
        [[ZToastManager ShardInstance] showtoast:[resultObject objectForKey:@"msg"]];
        if ([[resultObject objectForKey:@"code"] intValue]==1)
        {
            [[ZShare sharedInstance] initUserInfo:resultObject];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateuserinfo" object:nil];
            [_tbView reloadData];
            
        }
        
        
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] hideprogress];
        DLog(@"您取消了选择图片---%@",error);
    }];
}

@end
